<script>
  export default {
    name: 'CategorySelect',
    props: {
      show: {
        type: Boolean
      }
    },
    data () {
      return {
        // 表单存储的数据
        formInline: {
          c1Id: '',
          c2Id: '',
          c3Id: ''
        },
        // 三级分类的数据数组
        list1: [],
        list2: [],
        list3: []
      }
    },
    mounted () {
      this.getCategory1Fn()
    },
    methods: {
      // 获取三级分类id
      async handler3() {
        this.$emit('changeCategoryId', {categoryId: this.formInline.c3Id, level: 3})
      },
      // 二级分类改变，获取三级分类
      async handler2() {
        this.list3 = []
        this.formInline.c3Id = ''
        let res = await this.$API.attr.getCategory3(this.formInline.c2Id)
        this.$emit('changeCategoryId', {categoryId: this.formInline.c2Id, level: 2})
        if (res.code === 200) {
          this.list3 = res.data
        }
      },
      // 一级分类改变，获取二级分类
      async handler1() {
        this.list2 = []
        this.list3 = []
        this.formInline.c2Id = ''
        this.formInline.c3Id = ''
        let res = await this.$API.attr.getCategory2(this.formInline.c1Id)
        this.$emit('changeCategoryId', {categoryId: this.formInline.c1Id, level: 1})
        if (res.code === 200) {
          this.list2 = res.data
        }
      },
      // 获取默认一级分类的数据
      async getCategory1Fn() {
        let res = await this.$API.attr.getCategory1()
        // console.log(res);
        if (res.code === 200) {
          this.list1 = res.data
        }
      }
    }
  }
</script>

<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="一级分类">
        <el-select :disabled="show" v-model="formInline.c1Id" placeholder="请选择" @change="handler1">
          <el-option v-for="c1 in list1" :key="c1.id" :label="c1.name" :value="c1.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select :disabled="show" v-model="formInline.c2Id" placeholder="二级分类" @change="handler2">
          <el-option v-for="c2 in list2" :key="c2.id" :label="c2.name" :value="c2.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select :disabled="show" v-model="formInline.c3Id" placeholder="三级分类" @change="handler3">
          <el-option v-for="c3 in list3" :key="c3.id" :label="c3.name" :value="c3.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>

</style>